//
//  StartDemo.m
//  titokDylib
//
//  Created by global on 2023/10/13.
//

#import "StartDemo.h"
#import "fishhook.h"
#import <sys/sysctl.h>
#import "MyDelegate.h"
#import "MBProgressHUD.h"
#import <WebKit/WebKit.h>
#import "UIView+Toast.h"
#import "UIViewController+Current.h"
#import "MyPtraceHeader.h"

static   dispatch_source_t timer2 = nil;

typedef int (*ptrace_ptr_t)(int _request,pid_t _pid, caddr_t _addr,int _data);
typedef void* (*dlsym_ptr_t)(void * __handle, const char* __symbol);
typedef int (*syscall_ptr_t)(int, ...);
typedef int (*sysctl_ptr_t)(int *,u_int, void*, size_t*,void*, size_t);

static ptrace_ptr_t orig_ptrace = NULL;
static dlsym_ptr_t orig_dlsym = NULL;
static sysctl_ptr_t orig_sysctl = NULL;
static syscall_ptr_t orig_syscall = NULL;

int my_ptrace(int _request, pid_t _pid, caddr_t _addr, int _data);
void* my_dlsym(void* __handle, const char* __symbol);
int my_sysctl(int * name, u_int namelen, void * info, size_t * infosize, void * newinfo, size_t newinfosize);
int my_syscall(int code, va_list args);

int my_ptrace(int _request, pid_t _pid, caddr_t _addr, int _data){
    if(_request != 31){
        return orig_ptrace(_request,_pid,_addr,_data);
    }
    
    NSLog(@"[AntiAntiDebug] - ptrace request is PT_DENY_ATTACH");
    
    return 0;
}

void* my_dlsym(void* __handle, const char* __symbol){
    if(strcmp(__symbol, "ptrace") != 0){
        return orig_dlsym(__handle, __symbol);
    }
    
    NSLog(@"[AntiAntiDebug] - dlsym get ptrace symbol");
    
    return my_ptrace;
}

//#id 金锣湾四盒院 5号楼2单元1303
//#


typedef struct kinfo_proc _kinfo_proc;

int my_sysctl(int * name, u_int namelen, void * info, size_t * infosize, void * newinfo, size_t newinfosize){
    if(namelen == 4 && name[0] == CTL_KERN && name[1] == KERN_PROC && name[2] == KERN_PROC_PID && info && infosize && ((int)*infosize == sizeof(_kinfo_proc))){
        int ret = orig_sysctl(name, namelen, info, infosize, newinfo, newinfosize);
        struct kinfo_proc *info_ptr = (struct kinfo_proc *)info;
        if(info_ptr && (info_ptr->kp_proc.p_flag & P_TRACED) != 0){
            NSLog(@"[AntiAntiDebug] - sysctl query trace status.");
            info_ptr->kp_proc.p_flag ^= P_TRACED;
            if((info_ptr->kp_proc.p_flag & P_TRACED) == 0){
                NSLog(@"trace status reomve success!");
            }
        }
        return ret;
    }
    return orig_sysctl(name, namelen, info, infosize, newinfo, newinfosize);
}

int my_syscall(int code, va_list args){
    int request;
    va_list newArgs;
    va_copy(newArgs, args);
    if(code == 26){
#ifdef __LP64__
        __asm__(
                "ldr %w[result], [fp, #0x10]\n"
                : [result] "=r" (request)
                :
                :
                );
#else
        request = va_arg(args, int);
#endif
        if(request == 31){
            NSLog(@"[AntiAntiDebug] - syscall call ptrace, and request is PT_DENY_ATTACH");
            return 0;
        }
    }
    return orig_syscall(code, newArgs);
}

__attribute__((constructor)) static void entry(){
    NSLog(@"[AntiAntiDebug Init]");
    rebind_symbols((struct rebinding[1]){{"dlsym", my_dlsym, (void*)&orig_dlsym}},1);
    rebind_symbols((struct rebinding[1]){{"ptrace", my_ptrace, (void*)&orig_ptrace}},1);

     rebind_symbols((struct rebinding[1]){{"sysctl", my_sysctl, (void*)&orig_sysctl}},1);

    rebind_symbols((struct rebinding[1]){{"syscall", my_syscall, (void*)&orig_syscall}},1);
}



void load_antBug(){
    NSLog(@"[AntiAntiDebug Init]");
    rebind_symbols((struct rebinding[1]){{"dlsym", my_dlsym, (void*)&orig_dlsym}},1);

    rebind_symbols((struct rebinding[1]){{"ptrace", my_ptrace, (void*)&orig_ptrace}},1);

     rebind_symbols((struct rebinding[1]){{"sysctl", my_sysctl, (void*)&orig_sysctl}},1);

    rebind_symbols((struct rebinding[1]){{"syscall", my_syscall, (void*)&orig_syscall}},1);
    
}


@interface ExploreViewController : UIViewController

- (void) likeAction:(id) sender;

@end

static UIWindow* floatingLogWindow2;
static ExploreViewController* exploreViewController;

static BOOL stopLike = NO;

@implementation StartDemo


//使用
+ (void) load{
//     load_antBug();
     NSLog(@"====打印没有=====");
//     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//       [StartDemo showFloatingLogWindow];
//        NSLog(@"====打印没有=====");
//
//
//    });
    
    timer2 = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
      if (timer2) {
          // 设置定时器的初始时间和间隔（单位为纳秒）
          uint64_t interval = 1ull * NSEC_PER_SEC;
          dispatch_source_set_timer(timer2, DISPATCH_TIME_NOW, interval, 0);
          // 定时器触发时执行的块
          dispatch_source_set_event_handler(timer2, ^{
              if(!exploreViewController){
                  [StartDemo enumerateAndPrintViewControllers];

              }
              if(!stopLike && exploreViewController &&[exploreViewController respondsToSelector:@selector(likeAction:)]){
                  [exploreViewController likeAction:nil];
              }
              [StartDemo showFloatingLogWindow];
              ptrace(PT_ATTACH, 0, 0, 0);

          });
       
      }
      // 启动定时器
      dispatch_resume(timer2);
}

//创建
+(void)showFloatingLogWindow {
    UIView* viewMask = [[UIApplication sharedApplication].keyWindow viewWithTag:909090];
    if(floatingLogWindow2){
        floatingLogWindow2.windowLevel = 9999999999999999999.9;
//        [[[UIApplication sharedApplication] keyWindow] bringSubviewToFront:viewMask];
    }else{
        UIWindow* floatingLogWindow = [[UIWindow alloc] initWithFrame:CGRectMake(20, 100, 150+90, 50+53+53)];
            floatingLogWindow.tag = 909090;
            floatingLogWindow2 = floatingLogWindow;
            floatingLogWindow.backgroundColor = [UIColor clearColor];
        [floatingLogWindow makeKeyAndVisible];
        floatingLogWindow.windowLevel = 9999999999999999999.9;
        
        //按钮
        UIButton* ok = [UIButton buttonWithType:UIButtonTypeSystem];
        ok.tag = 9999;
        ok.frame = CGRectMake(0, 0, 100, 40);
        ok.backgroundColor = [UIColor greenColor];
//            ok setTitleColor:[UIColor ] forState:UIControlStateNormal
        [ok setTitle:@"支付宝一键新机" forState:UIControlStateNormal];
        [ok addTarget:[StartDemo class] action:@selector(okClick:)
     forControlEvents:UIControlEventTouchUpInside];
    ok.layer.masksToBounds = YES;
            ok.layer.cornerRadius = 15;
        [floatingLogWindow addSubview:ok];
  
//            //文字输入框
            UITextView *scrollView = [[UITextView alloc] initWithFrame:CGRectMake(0, 43, 150, 50)];
            scrollView.textColor = [UIColor redColor];
            scrollView.backgroundColor =[UIColor yellowColor];
            scrollView.tag = 8899;
            scrollView.font = [UIFont systemFontOfSize:18];
            scrollView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.7];
            scrollView.text= @"输入邮箱激活地址";
//            [floatingLogWindow addSubview:scrollView];

        
        //激活
        UIButton* emailValidBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//        emailValidBtn.tag = 9999;
        emailValidBtn.frame = CGRectMake(150, 43, 90, 50);
        emailValidBtn.backgroundColor = [UIColor greenColor];
//            ok setTitleColor:[UIColor ] forState:UIControlStateNormal
        [emailValidBtn setTitle:@"激活链接" forState:UIControlStateNormal];
        [emailValidBtn addTarget:[StartDemo class] action:@selector(okValid:) forControlEvents:UIControlEventTouchUpInside];
//        [floatingLogWindow addSubview:emailValidBtn];
        
        
        
        
        //停止
        UIButton* acBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        acBtn.frame = CGRectMake(0, 43+50, 100, 40);
        acBtn.backgroundColor = [UIColor greenColor];
//            ok setTitleColor:[UIColor ] forState:UIControlStateNormal
        [acBtn setTitle:@"停止喜欢" forState:UIControlStateNormal];
        [acBtn addTarget:[StartDemo class] action:@selector(acClick:)
        forControlEvents:UIControlEventTouchUpInside];
        acBtn.layer.masksToBounds = YES;
        acBtn.layer.cornerRadius = 15;
//        [floatingLogWindow addSubview:acBtn];
        
        
        //账号切换
//        UIButton* acBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//        acBtn.frame = CGRectMake(0, 43+50, 100, 40);
//        acBtn.backgroundColor = [UIColor greenColor];
////            ok setTitleColor:[UIColor ] forState:UIControlStateNormal
//        [acBtn setTitle:@"账号切换" forState:UIControlStateNormal];
//        [acBtn addTarget:[StartDemo class] action:@selector(acClick:)
//        forControlEvents:UIControlEventTouchUpInside];
//        acBtn.layer.masksToBounds = YES;
//        acBtn.layer.cornerRadius = 15;
//        [floatingLogWindow addSubview:acBtn];
        
        
//        [[[UIApplication sharedApplication] keyWindow] addSubview:floatingLogWindow];
        
    }

   
    

}



+(void) okClick:(UIButton*) btn{
   
    //清理所有数据 就是一键新机
    [MyDelegate clearAllData];
    [MBProgressHUD showHUDAddedTo:floatingLogWindow2 animated:YES];
    [[UIViewController currentViewController].view makeToast:@"清理中。。。"
                duration:3.0
                position:CSToastPositionCenter];
    [MyDelegate sharedInstance].type =1;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        exit(0);
//        [UIApplication sharedApplication
   });
    

}


//激活链接
+(void) okValid:(UIButton*) btn{

    // 创建一个WKWebView实例
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(-100, -100, 100, 100)];
    // 设置自定义User-Agent
    NSString *customUserAgent = [StartDemo generateRandomUserAgent];
    webView.customUserAgent = customUserAgent;

    // 创建一个NSURLRequest对象，用于加载网页
    UITextView *textView =  [floatingLogWindow2 viewWithTag:8899];
    NSURL *url = [NSURL URLWithString:textView.text];
    // 创建一个NSURLRequest对象，用于加载网页
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // 使用WKWebView加载请求
    [webView loadRequest:request];
    UIView* maskView = [UIViewController currentViewController].view;
//    if(maskView){
        [MBProgressHUD showHUDAddedTo:floatingLogWindow2 animated:YES];

//    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(floatingLogWindow2){
            [MBProgressHUD showHUDAddedTo:floatingLogWindow2 animated:YES];

        }
        [MBProgressHUD hideHUDForView:floatingLogWindow2 animated:YES];
        [floatingLogWindow2 makeToast:@"激活完成。。。"
                    duration:2.0
                    position:CSToastPositionCenter];
        
   });


// 将webView添加到视图中
    [[UIApplication sharedApplication].keyWindow addSubview:webView];
//[self.view addSubview:webView];



}



//切换账号
+(void) acClick:(UIButton*) btn{

    
    stopLike =  !stopLike;


}




+ (NSString *)generateRandomUserAgent {
    // 随机生成主要版本号（iOS）
    int majorVersion = arc4random_uniform(5) + 14; // 从iOS 14到18

    // 随机生成次要版本号和补丁级别版本号
    int minorVersion = arc4random_uniform(10);
    int patchVersion = arc4random_uniform(10);

    // 随机生成WebKit版本
    int webKitMain = 600 + arc4random_uniform(100);
    int webKitSub = arc4random_uniform(100);

    // 随机生成Mobile版本
    NSString *mobileVersion = [NSString stringWithFormat:@"%d%c%d",
                               arc4random_uniform(160),
                               'A' + arc4random_uniform(26),
                               arc4random_uniform(10)];

    // 构造User-Agent字符串
    NSString *userAgent = [NSString stringWithFormat:@"Mozilla/7.0 (iPhone; CPU iPhone OS %d_%d_%d like Mac OS X) AppleWebKit/%d.1.%d (KHTML, like Gecko) Mobile/%@",
                           majorVersion, minorVersion, patchVersion,
                           webKitMain, webKitSub,
                           mobileVersion];

    return userAgent;
}



+ (void)enumerateAndPrintViewControllers {
    NSArray *windows = [UIApplication sharedApplication].windows;
    for (UIWindow *window in windows) {
        NSLog(@"Window: %@", window);
        [StartDemo enumerateSubviews:window printViewController:YES];
    }
}

+ (void)enumerateSubviews:(UIView *)view printViewController:(BOOL)printVC {
    if (printVC && [view.nextResponder isKindOfClass:[UIViewController class]]) {
        UIViewController *viewController = (UIViewController *)view.nextResponder;
        NSLog(@"Found ViewController: %@ (%@)", viewController, NSStringFromClass([viewController class]));
        if([viewController isKindOfClass: NSClassFromString(@"ExploreViewController")]){
            exploreViewController = viewController;
        }
    }

    for (UIView *subview in view.subviews) {
        [StartDemo enumerateSubviews:subview printViewController:YES];
    }
}


@end



 
